package com.eric.common.file;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;


public class CutFile {
	String fileName;
	File file;
	int numOfCuts;
	int cutPoints;
	
	public static void main (String args[]) throws Exception {
		String f = "/home/eric/tmp/test.txt";
		System.out.println(new CutFile(f,3).Cut());
//		System.out.println(new CutFile(f,3).NumOfCuts());
	}
	
	public CutFile (String fileName,int cutPoints) throws IOException {
		this.fileName = fileName;
		numOfCuts = NumOfCuts();
		this.cutPoints = cutPoints;
	}
	
	public int NumOfCuts () throws IOException {
		double numOfLines = new FileStats().CountLines(fileName);
		return(int) Math.ceil(numOfLines / cutPoints);
	}
   
	public HashSet<String> Cut () throws Exception {
		File f = new File(fileName);
		String path = f.getParent();
		String targetFileName = path+"/"+f.getName();
		HashSet<String> splitFiles = new HashSet<String>();
	    List<String> li = new ArrayList<String>();
		
		FileReader fileReader = new FileReader(f);
	    BufferedReader br = new BufferedReader(fileReader);
//	    FileStats fstats = new FileStats();
	    JSave saver = new JSave();
	    
	    String line;
	    int i = 1;
//	    int lineNum = 1;
//	    int add = cutPoints;
//	    	while ((line = br.readLine()) != null ) {
//	    		if (lineNum <= cutPoints) {
//	    			saver.Add(targetFileName+"."+i, line);
//	    			li.add(line);
//	    			splitFiles.add(targetFileName+"."+i);
//	    		}else{
//	    			saver.Add(targetFileName+"."+i, li);
//	    			li.clear();
//	    			li.add(line);
//	    			splitFiles.add(targetFileName+"."+i);
//	    			
//	    			cutPoints = cutPoints + add;
//	    			i++;
//	    			saver.Add(targetFileName+"."+i, line);
//	    		}
//	    		lineNum++;
//	    	}
	    while ((line = br.readLine()) != null){
	    	String output = targetFileName+"."+i;
	    	
	    	if (li.size() < cutPoints ) {
	    		li.add(line);

	    	} else {	    	
	    		saver.Add(output, li);
	    		splitFiles.add(output);
	    		li.clear();
	    		
	    		i++;
	    		li.add(line);
	    	}
	    }
	    if (li.size() > 0) {
	    	String output = targetFileName+"."+i;
	    	saver.Add(output, li);
    		splitFiles.add(output);
    		li.clear();
	    }
	    
	    br.close();
	    return splitFiles;
	}
	
}